package com.crop.back.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crop.back.common.enums.Deleted;
import com.crop.back.common.enums.RoleEnum;
import com.crop.back.common.utils.ResultBean;
import com.crop.back.common.utils.UserHolder;
import com.crop.back.dto.ProductDTO;
import com.crop.back.dto.UserDTO;
import com.crop.back.entity.Product;
import com.crop.back.entity.ProductCategory;
import com.crop.back.entity.ProductRecord;
import com.crop.back.entity.Supplier;
import com.crop.back.service.ProductCategoryService;
import com.crop.back.service.ProductService;
import com.crop.back.service.SupplierService;
import org.bouncycastle.util.Pack;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;

/**
 * <p>
 * 产品表 前端控制器
 * </p>
 *
 * @author 作者
 * @since 2025-01-20
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Resource
    private ProductService productService;
    @Resource
    private SupplierService supplierService;

    @Resource
    private ProductCategoryService productCategoryService;

    @GetMapping("/name")
    public ResultBean getName() {
        UserDTO user = UserHolder.getUser();
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getDeleted, Deleted.NOT_DELETED.getCode());
        if (user.getRoleId() == RoleEnum.SUPPLIER.getCode()) {
            queryWrapper.eq(Product::getSupplierId, UserHolder.getUser().getReferenceId());
        }
        List<Product> list = productService.list(queryWrapper);
        return ResultBean.ok(list);
    }

    @PostMapping("/list")
    public ResultBean getAll(@RequestBody ProductDTO productDTO) {
        try {
            Integer page = productDTO.getPage();
            Integer pageSize = productDTO.getPageSize();
            Page<Product> pageInfo = new Page<>(page, pageSize);
            Map<Long, String> map1 = supplierService
                    .list(new LambdaQueryWrapper<Supplier>().eq(Supplier::getDeleted, Deleted.NOT_DELETED.getCode()))
                    .stream()
                    .collect(Collectors.toMap(
                            Supplier::getId,
                            Supplier::getName
                    ));
            Map<Long, String> map2 = productCategoryService
                    .list(new LambdaQueryWrapper<ProductCategory>().eq(ProductCategory::getDeleted, Deleted.NOT_DELETED.getCode()))
                    .stream()
                    .collect(Collectors.toMap(
                            ProductCategory::getId,
                            ProductCategory::getName
                    ));
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getDeleted, Deleted.NOT_DELETED.getCode());

            if (UserHolder.getUser().getRoleId() == RoleEnum.SUPPLIER.getCode()) {
                queryWrapper.eq(Product::getSupplierId, UserHolder.getUser().getReferenceId());
            }


            Page<Product> pageRes = productService.page(pageInfo, queryWrapper);

            List<ProductDTO> collect = pageRes.getRecords()
                    .stream()
                    .map(item -> {
                        ProductDTO dto = BeanUtil.copyProperties(item, ProductDTO.class);
                        dto.setSupplierName(map1.getOrDefault(dto.getSupplierId(), "暂无"));
                        dto.setCategoryName(map2.getOrDefault(dto.getCategoryId(), "暂无"));
                        return dto;
                    }).collect(Collectors.toList());
            return ResultBean.ok(collect, pageRes.getTotal());
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return ResultBean.fail("查找失败");
        }
    }

    @PostMapping("/get")
    public ResultBean getByCondition(@RequestBody ProductDTO productDTO) {
        try {
            Integer page = productDTO.getPage();
            Integer pageSize = productDTO.getPageSize();
            Page<Product> pageInfo = new Page<>(page, pageSize);

            Map<Long, String> map1 = supplierService
                    .list(new LambdaQueryWrapper<Supplier>().eq(Supplier::getDeleted, Deleted.NOT_DELETED.getCode()))
                    .stream()
                    .collect(Collectors.toMap(
                            Supplier::getId,
                            Supplier::getName
                    ));
            Map<Long, String> map2 = productCategoryService
                    .list(new LambdaQueryWrapper<ProductCategory>().eq(ProductCategory::getDeleted, Deleted.NOT_DELETED.getCode()))
                    .stream()
                    .collect(Collectors.toMap(
                            ProductCategory::getId,
                            ProductCategory::getName
                    ));
            List<Long> supplierIdList = supplierService
                    .list(new LambdaQueryWrapper<Supplier>()
                            .eq(Supplier::getDeleted, Deleted.NOT_DELETED.getCode())
                            .like(productDTO.getSupplierName() != null, Supplier::getName, productDTO.getSupplierName()))
                    .stream()
                    .map(Supplier::getId)
                    .toList();
            List<Long> categoryIdList = productCategoryService
                    .list(new LambdaQueryWrapper<ProductCategory>()
                            .eq(ProductCategory::getDeleted, Deleted.NOT_DELETED.getCode())
                            .like(productDTO.getCategoryName() != null, ProductCategory::getName, productDTO.getCategoryName()))
                    .stream()
                    .map(ProductCategory::getId)
                    .toList();

            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getDeleted, Deleted.NOT_DELETED.getCode());
            queryWrapper.like(productDTO.getName() != null, Product::getName, productDTO.getName());
            if (productDTO.getSupplierName() != null && supplierIdList.isEmpty()) {
                return ResultBean.ok();
            }
            if (productDTO.getCategoryName() != null && categoryIdList.isEmpty()) {
                return ResultBean.ok();
            }
            queryWrapper.in(!supplierIdList.isEmpty(), Product::getSupplierId, supplierIdList);
            queryWrapper.in(!categoryIdList.isEmpty(), Product::getCategoryId, categoryIdList);

            String supplierName = UserHolder.getUser().getUserName();
            Supplier one = supplierService.getOne(new LambdaQueryWrapper<Supplier>()
                    .eq(Supplier::getDeleted, Deleted.NOT_DELETED.getCode())
                    .eq(supplierName != null, Supplier::getName, supplierName));
            if (UserHolder.getUser().getRoleId() == RoleEnum.SUPPLIER.getCode()) {
                queryWrapper.eq(one != null, Product::getSupplierId, one.getId());
                queryWrapper.eq(Product::getSupplierId, UserHolder.getUser().getReferenceId());
            }

            Page<Product> pageRes = productService.page(pageInfo, queryWrapper);
            List<ProductDTO> collect = pageRes.getRecords()
                    .stream()
                    .map(item -> {
                        ProductDTO dto = BeanUtil.copyProperties(item, ProductDTO.class);
                        dto.setSupplierName(map1.getOrDefault(dto.getSupplierId(), "暂无"));
                        dto.setCategoryName(map2.getOrDefault(dto.getCategoryId(), "暂无"));
                        return dto;
                    }).collect(Collectors.toList());
            return ResultBean.ok(collect, pageRes.getTotal());
        } catch (Exception e) {
            return ResultBean.fail("查找失败");
        }
    }

    @PostMapping("/save")
    public ResultBean addOrUpdate(@RequestBody ProductDTO productDTO) {
        try {

            Product product = BeanUtil.copyProperties(productDTO, Product.class);
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getDeleted, Deleted.DELETED.getCode())
                    .eq(product.getName() != null, Product::getName, product.getName());
            Product one = productService.getOne(queryWrapper);
            if (one != null) {
                productService.removeById(one.getId());
            }
            if (productDTO.getId() == null) {
                productService.save(product);
                return ResultBean.ok("添加成功");
            } else {
                productService.updateById(product);
                return ResultBean.ok("修改成功");
            }
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry") || e.getCause().getMessage().contains("Duplicate entry")) {
                return ResultBean.fail("产品名已存在，请检查重复项");
            }
            return ResultBean.fail("保存失败");
        }

    }

    @DeleteMapping("/delete/{id}")
    public ResultBean delete(@PathVariable("id") Long id) {
        try {
            LambdaUpdateWrapper<Product> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Product::getId, id);
            updateWrapper.set(Product::getDeleted, Deleted.DELETED.getCode());
            productService.update(updateWrapper);
            return ResultBean.ok();
        } catch (Exception e) {
            return ResultBean.fail("删除失败");
        }
    }
}
